package service;

import beans.UseOrder;
import db.UseOrderDao;
import java.sql.SQLException;
import java.sql.Date;
import beans.Shenqing;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class UseOrderService {
    private UseOrderDao useOrderDao;

    public UseOrderService() {
        this.useOrderDao = new UseOrderDao();
    }

    // 添加用车订单
    public boolean addUseOrder(UseOrder order) {
        try {
            return useOrderDao.insertUseOrder(order);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 创建用车订单（兼容旧代码）
    public boolean createUseOrder(UseOrder order) {
        //System.out.println("createUseOrder_Service (Original)"); // 可以保留或移除调试输出
        return addUseOrder(order);
    }

    // 根据员工ID获取订单
    public List<UseOrder> getOrdersByEmployeeId(int employeeId) {
        try {
            return useOrderDao.getOrdersByEmployeeId(employeeId);
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>(); // 返回空列表而不是null，避免空指针异常
        }
    }

    // 根据订单号和员工ID获取订单
    public UseOrder getOrderByIdAndEmployeeId(String orderId, int employeeId) {
        try {
            return useOrderDao.getOrderByIdAndEmployeeId(orderId, employeeId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 获取员工的最新订单
    public UseOrder getLatestOrderByEmployeeId(int employeeId) {
        try {
            return useOrderDao.getLatestOrderByEmployeeId(employeeId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 检查订单是否存在
    public boolean orderExists(String orderId) {
        try {
            return useOrderDao.orderExists(orderId);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 根据订单号获取订单（不限制员工ID）
    public UseOrder getOrderById(String orderId) {
        try {
            return useOrderDao.getOrderById(orderId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 获取所有订单
    public List<UseOrder> getAllUseOrders() {
        try {
            return useOrderDao.getAllUseOrders();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    //搜索
    public List<UseOrder> searchOrders(String orderId, String employeeIdStr,
                                       String status, String startDateStr,
                                       String endDateStr,int i) {
        // 参数转换
        Integer employeeId = null;
        try {
            if (employeeIdStr != null && !employeeIdStr.isEmpty()) {
                employeeId = Integer.parseInt(employeeIdStr);
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("员工ID必须为数字");
        }

        java.util.Date startDate = parseDate(startDateStr);
        Date endDate = (Date) parseDate(endDateStr);

        return useOrderDao.searchOrders(orderId, employeeId, status, startDate, endDate,i);
    }

    //查询已经处理的订单
    public List<UseOrder> getProcessedOrders() {
        System.out.println("11111111service");
        return useOrderDao.findByStatusNot("待审核");
    }

    //查询待审核订单
    public List<UseOrder> getOrders() {
        return useOrderDao.findByStatus("待审核");
    }

    private java.util.Date parseDate(String dateStr) {
        if (dateStr == null || dateStr.isEmpty()) return null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(dateStr);
        } catch (ParseException e) {
            throw new IllegalArgumentException("日期格式错误");
        }
    }

    // 更新订单
    public boolean updateUseOrder(UseOrder order) {
        try {
            return useOrderDao.updateUseOrder(order);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 删除订单
    public boolean deleteUseOrder(String orderId) {
        try {
            return useOrderDao.deleteUseOrder(orderId);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 根据ID获取订单
    public UseOrder getUseOrderById(String orderId) {
        try {
            return useOrderDao.getUseOrderById(orderId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 搜索订单
    public List<UseOrder> searchUseOrders(String keyword) {
        try {
            return useOrderDao.searchUseOrders(keyword);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    public UseOrder getOrderById(int orderId) throws SQLException {
        return useOrderDao.getOrderById(orderId);
    }

    public boolean updateOrderStatus(String orderId, String status) {
        try {
            // 先检查订单是否存在
            UseOrder order = useOrderDao.getOrderById(orderId);
            if (order == null) {
                return false;
            }
            
            // 检查订单状态是否为"已通过"
            if (!"已通过".equals(order.getReviewStatus())) {
                return false;
            }
            
            // 更新订单状态
            return useOrderDao.updateOrderStatus(orderId, status);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 创建新的用车订单，根据申请信息，处理int字段为0时插入NULL
     * @param useOrder 待创建的用车订单对象
     * @return boolean 插入成功返回true，否则返回false
     */
    public boolean createUseOrderByShenqing(UseOrder useOrder) {
        if (useOrder == null) {
            return false;
        }

        // 验证必要字段
        if (useOrder.getOrderId() == null || useOrder.getOrderId().trim().isEmpty()) {
            return false;
        }

        if (useOrder.getEmployeeId() <= 0) {
            return false;
        }

        if (useOrder.getDriverId() <= 0) {
            return false;
        }

        if (useOrder.getVehicleId() <= 0) {
            return false;
        }

        if (useOrder.getExpectedDepartureTime() == null || useOrder.getExpectedReturnTime() == null) {
            return false;
        }

        if (useOrder.getExpectedDepartureTime().after(useOrder.getExpectedReturnTime())) {
            return false;
        }

        if (useOrder.getReviewStatus() == null || !"已通过".equals(useOrder.getReviewStatus())) {
            return false;
        }

        if (useOrder.getReviewer() == null) {
            return false;
        }

        // 检查订单是否已存在
        try {
            if (useOrderDao.orderExists(useOrder.getOrderId())) {
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }

        // 调用DAO层方法插入数据
        return useOrderDao.insertUseOrderByShenqing(useOrder);
    }

}